package com.example.forum.controller;
import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtils;
import com.sun.org.apache.bcel.internal.generic.FADD;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.el.parser.AstFalse;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import javax.xml.ws.http.HTTPBinding;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    /**
     * 注册功能
     * @param username  用户名
     * @param nickname  用户昵称
     * @param password  用户密码
     * @param passwordRepeat  确认密码
     * @param email  邮箱地址（可选）
      * @return
     */
    @ApiOperation("用户注册接口")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NotNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NotNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NotNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NotNull String passwordRepeat,
                              @ApiParam("邮箱") @RequestParam(value = "email", required = false) String email){
        //校验参数
//        if(!StringUtil.isEmpty(username)||!StringUtil.isEmpty(password)||
//                !StringUtil.isEmpty(nickname)||!StringUtil.isEmpty(passwordRepeat)){
//            //返回错误信息
//            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//        }
        //校验两次密码必须相同
            if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //打印错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //准备数据
        User user=new User();
        user.setUsername(username);
        user.setNickname(nickname);
        // 设置邮箱（如果有）
        if(!StringUtil.isEmpty(email)) {
            user.setEmail(email);
        }
        //对密码加盐
        String salt= UUIDUtils.UUID_32();
        String encryptPassword=MD5Util.md5Salt(password,salt);
        log.info(username+"密码为"+password);
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        //执行添加操作
        userService.createNormalUser(user);
        //返回成功
        return AppResult.success();
    }

    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public AppResult login(@ApiParam("用户名") @RequestParam("username") @NotNull String username,
                           @ApiParam("密码") @RequestParam("password") @NotNull String password, HttpServletRequest request){

        log.info("用户登录请求: username={}, IP={}", username, request.getRemoteAddr());
        
        //验证登录
        User user=userService.login(username,password);
        if(user==null||user.getId()<=0){
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + "用户名: " + username);

            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        
        log.info("用户登录成功: id={}, username={}", user.getId(), user.getUsername());
        
        // 获取用户统计信息
        Map<String, Object> stats = userService.getUserStats(user.getId());
        
        // 设置统计数据
        user.setCommentCount((Integer)stats.get("commentCount"));
        user.setLikeCount((Integer)stats.get("likeCount"));
        
        //登录成功 存储Session
        HttpSession session=request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        log.info("用户会话已创建: sessionId={}, userId={}", session.getId(), user.getId());
        
        //返回结果，包含用户信息
        return AppResult.success(user);
    }

    /**
     * 获取用户信息 两部分
     * 如果是点击个人中心  从Session中是查询自己的信息
     * 如果是点击别人主页 则根据id查询该用户信息
     * @param request  获取Session
     * @param id  传入的用户id
     * @return  查询到的用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,  //设置id为非必传项
                                       @ApiParam("用户id") @RequestParam(value = "id",required = false)
                                       Long id){
        //1.如果id为空 从当前登陆信息中查询用户信息
        User user = null;
        if(id == null){
            //从session获取登录信息
            HttpSession session = request.getSession(false);
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
            if (user == null) {
                return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
            }
            id = user.getId();
        } else {
            //如果不为空 从数据库中查询指定id的用户信息
            user = userService.selectById(id);
            if(user == null || user.getId() <= 0){
                return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
            }
        }
        
        // 获取用户统计信息
        Map<String, Object> stats = userService.getUserStats(id);
        
        // 直接将统计数据设置到用户对象中
        user.setCommentCount((Integer)stats.get("commentCount"));
        user.setLikeCount((Integer)stats.get("likeCount"));
        
        // 更新当前会话中的用户信息
        if(id.equals(user.getId())) {
            HttpSession session = request.getSession(false);
            if(session != null) {
                session.setAttribute(AppConfig.USER_SESSION, user);
            }
        }
        
        // 返回用户对象
        return AppResult.success(user);
    }
    
    /**
     * 获取用户统计信息
     */
    @ApiOperation("获取用户统计信息")
    @GetMapping("/stats")
    public AppResult<Map<String, Object>> getUserStats(
            HttpServletRequest request,
            @ApiParam("用户id") @RequestParam(value = "id", required = false) Long id) {
            
        // 如果id为空，使用当前登录用户的id
        if (id == null) {
            HttpSession session = request.getSession(false);
            if (session == null) {
                return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
            }
            
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            if (user == null) {
                return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
            }
            
            id = user.getId();
        }
        
        // 获取用户统计信息
        Map<String, Object> stats = userService.getUserStats(id);
        
        return AppResult.success(stats);
    }
    
    /**
     * 退出功能 注销Session
     */
    @ApiOperation("注销功能")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        //获取session
        HttpSession session=request.getSession(false);
        if(session!=null){
            //打印日志
            log.info("退出成功");
            //表示用户已登陆  销毁Session
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,@ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false) String email,
                                @ApiParam("电话号码") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark
                                ){
        //对参数进行非空校验  如果都为空 返回错误结果
        if(StringUtil.isEmpty(username)&&StringUtil.isEmpty(nickname)&&
        StringUtil.isEmpty(email)&&StringUtil.isEmpty(phoneNum)&&StringUtil.isEmpty(remark)&&gender==null){
            return AppResult.failed("请输入修改信息");
        }
        //获取当前用户信息
        HttpSession session =request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        //构造修改对象
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        //执行方法
        userService.modifyInfo(updateUser);
        //查询最新的用户信息  返回
        user=userService.selectById(user.getId());
        
        // 获取用户统计信息
        Map<String, Object> stats = userService.getUserStats(user.getId());
        
        // 设置统计数据
        user.setCommentCount((Integer)stats.get("commentCount"));
        user.setLikeCount((Integer)stats.get("likeCount"));
        
        //把最新的用户信息色设置到Session
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("老密码") @RequestParam("oldPassword") @NotNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NotNull String newPassword,
                                    @ApiParam("重复新密码") @RequestParam("passwordRepeat") @NotNull String passwordRepeat){
        //获取当前登录用户
        HttpSession session=request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验参数 两次密码输入是否一致
        if(!newPassword.equals(passwordRepeat)){
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        if(oldPassword.equals(newPassword)){
            return AppResult.failed("新密码和老密码不能一致");
        }
        //校验通过 调用Services
        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        //销毁Session
        if(session!=null){
            session.invalidate();
        }
        return AppResult.success();
    }
    
    /**
     * 获取活跃用户列表
     * @param limit 返回的用户数量，默认为5
     * @return 活跃用户列表
     */
    @ApiOperation("获取活跃用户")
    @GetMapping("/active")
    public AppResult<List<User>> getActiveUsers(
            @ApiParam("返回数量限制") @RequestParam(value = "limit", defaultValue = "5") Integer limit) {
        
        // 参数校验
        if (limit <= 0) {
            limit = 5;
        }
        
        try {
            // 获取活跃用户列表 - 这是公共数据，无需登录也可以访问
            List<User> activeUsers = userService.getActiveUsers(limit);
            
            // 保护用户隐私，过滤掉敏感信息
            for (User user : activeUsers) {
                // 隐藏密码、盐值等敏感信息
                user.setPassword(null);
                user.setSalt(null);
                user.setEmail(null);
                user.setPhoneNum(null);
            }
            
            return AppResult.success(activeUsers);
        } catch (Exception e) {
            log.error("获取活跃用户失败", e);
            return AppResult.failed("获取活跃用户列表失败");
        }
    }

    /**
     * 获取当前登录用户信息（测试用）
     */
    @ApiOperation("获取当前登录用户信息（测试用）")
    @GetMapping("/current")
    public AppResult<Map<String, Object>> getCurrentUser(HttpServletRequest request) {
        // 从会话获取用户
        HttpSession session = request.getSession(false);
        if (session == null) {
            log.warn("获取当前用户信息失败：会话不存在");
            return AppResult.failed("会话不存在");
        }
        
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user == null) {
            log.warn("获取当前用户信息失败：用户未登录");
            return AppResult.failed("用户未登录");
        }
        
        // 记录授权头信息
        String authHeader = request.getHeader("Authorization");
        
        // 构造返回信息
        Map<String, Object> result = new HashMap<>();
        result.put("id", user.getId());
        result.put("username", user.getUsername());
        result.put("nickname", user.getNickname());
        result.put("sessionId", session.getId());
        result.put("authorization", authHeader);
        
        log.info("获取当前用户信息：用户ID={}, 用户名={}, 会话ID={}", 
                user.getId(), user.getUsername(), session.getId());
        
        return AppResult.success(result);
    }
}
